/**
 * 派工单排程
 */
$(function() {
    var WeekDay;
    //Unix时间转为正常时间表示
    function FormatDateTime(UnixTime) {
        var date = new Date(parseInt(UnixTime));
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        return h + ':' + minute;
    }
    //计算不同工作时间对应的不同表格id
    function ShowDateinTable(StartTime,EachChosenDay){
        var day=null;
        var time=null;
        var index=null;
        switch(EachChosenDay){
            case "周一":day=0;break;
            case "周二":day=1;break;
            case "周三":day=2;break;
            case "周四":day=3;break;
            case "周五":day=4;break;
            case "周六":day=5;break;
            case "周日":day=6;break;
        }
        for(var i=7*time;i<7*(time+1);i++){
            var cal=(i-day)%7;
            if(cal==0){index=i;break;}
        }
        return index;
    }
    //第一周日期
    function ShowFirstWeekDateTitle(){
        var arr = [];
        var today = new Date();
        for(var i=0;i<6;i++){
            var date = new Date(today.getFullYear(), today.getMonth(), today.getDate()-today.getDay()+i+1);
            arr[date.getDay()] = date;
        }
        var sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate()-today.getDay()+7);
        arr[sunday.getDay()]=sunday;
        document.getElementById('monday').innerText=arr[1].getMonth() + 1 + "/" + arr[1].getDate();
        document.getElementById('tuesday').innerText=arr[2].getMonth() + 1 + "/" + arr[2].getDate();
        document.getElementById('wednesday').innerText=arr[3].getMonth() + 1 + "/" + arr[3].getDate();
        document.getElementById('thursday').innerText=arr[4].getMonth() + 1 + "/" + arr[4].getDate();
        document.getElementById('friday').innerText=arr[5].getMonth() + 1 + "/" + arr[5].getDate();
        document.getElementById('saturday').innerText=arr[6].getMonth() + 1 + "/" + arr[6].getDate();
        document.getElementById('sunday').innerText=arr[0].getMonth() + 1 + "/" + arr[0].getDate();
    }
    //第二周日期
    function ShowSecondWeekDateTitle(){
        var arr = [];
        var today = new Date();
        for(var i=0;i<7;i++){
            var date = new Date(today.getFullYear(), today.getMonth(), today.getDate()-today.getDay()+i+7);
            arr[date.getDay()] = date;
        }
        var sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate()-today.getDay()+14);
        arr[sunday.getDay()]=sunday;
        document.getElementById('monday').innerText=arr[1].getMonth() + 1 + "/" + arr[1].getDate();
        document.getElementById('tuesday').innerText=arr[2].getMonth() + 1 + "/" + arr[2].getDate();
        document.getElementById('wednesday').innerText=arr[3].getMonth() + 1 + "/" + arr[3].getDate();
        document.getElementById('thursday').innerText=arr[4].getMonth() + 1 + "/" + arr[4].getDate();
        document.getElementById('friday').innerText=arr[5].getMonth() + 1 + "/" + arr[5].getDate();
        document.getElementById('saturday').innerText=arr[6].getMonth() + 1 + "/" + arr[6].getDate();
        document.getElementById('sunday').innerText=arr[0].getMonth() + 1 + "/" + arr[0].getDate();
    }
    // 护理日多选框
    layui.config({
        base: '/js/dist/'
    }).extend({
        xmSelect: 'xm-select'
    }).use(['xmSelect'], function(){
        var xmSelect = layui.xmSelect;
        //渲染多选
        WeekDay = xmSelect.render({
            el: '#chosen_weekday',
            data: [
                {name: '周一', value: '周一'},
                {name: '周二', value: '周二'},
                {name: '周三', value: '周三'},
                {name: '周四', value: '周四'},
                {name: '周五', value: '周五'},
                {name: '周六', value: '周六'},
                {name: '周日', value: '周日'}
            ]
        });
    });

    dateArrangeInfo();
    function dateArrangeInfo() {
        layui.use(['table', 'form', 'element', 'laydate', 'layer', 'tree','util'], function () {
            var $ = layui.$;
            var table = layui.table;
            var form = layui.form;
            var element = layui.element;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var util = layui.util;
            var tree = layui.tree;
            console.log("进入dateArrangeInfo.js");

            // 派工单信息页面对指定老人选择“排程”按钮后，在该页面自动填充内容
            var elderYbid=window.parent.document.getElementById("transferElderYbid").value;//所选订单的老人医保ID
            var ArrangeID=window.parent.document.getElementById("transferArrangeID").value;//所选订单的ID

            //后台根据医保ID搜索老人信息，并显示
            if(elderYbid!=null && elderYbid!=""){
                console.log("根据老人ID查找");
                $.ajax({
                    type:"GET"
                    ,url: "/arrangeInfo/findElderInfobyYbid"
                    ,data: {elderYbid:elderYbid}
                    ,dataType: "JSON"
                    ,success: function(result) {
                        console.log("成功获取");
                        console.log(result[0]);
                        document.getElementById('elderName').value=result[0].name;
                        document.getElementById('elderLevel').value=result[0].person_level;
                        document.getElementById('elderGender').value=result[0].gender;
                        document.getElementById('elderAge').value=result[0].age;
                        document.getElementById('elderID').value=result[0].id_number;
                        document.getElementById('elderYbid').value=result[0].ybid;
                        document.getElementById('elderPhone').value=result[0].phone_number;
                    }
                });
            }

            var tableIns = table.render({
                elem: '#servDayChosen'
                , id: 'servDayChosen'
                , url: '/arrangeInfo/showDateArrangeInfo'
                , height: 100
                , cellMinWidth: 100//全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , limit: 1
                , where:{
                    ArrangeID:ArrangeID
                }
                , request: {
                    pageName: 'pn' //页码的参数名称，默认：page
                    , limitName: 'limit' //每页数据量的参数名，默认：limit
                }
                , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": 0, //解析接口状态
                        "msg": '', //解析提示文本
                        "count": res.total, //解析数据长度
                        "data": res.list //解析数据列表
                    }
                }
                , cols: [[
                    {field: 'serv_monday', title: '周一'}
                    , {field: 'serv_tuesday', title: '周二'}
                    , {field: 'serv_wednesday', title: '周三'}
                    , {field: 'serv_thursday', title: '周四'}
                    , {field: 'serv_friday', title: '周五'}
                    , {field: 'serv_saturday', title: '周六'}
                    , {field: 'serv_sunday', title: '周日'}
                ]]
            });
            var tableIns1=table.render({
                elem: '#nursingInfoList'
                ,id:'nursingArrange'
                ,url:'/staff/showNursingInfo'
                ,height:300
                ,cellMinWidth: 80//全局定义常规单元格的最小宽度，layui 2.2.1 新增
                ,request:{
                    pageName: 'pn' //页码的参数名称，默认：page
                    ,limitName: 'limit' //每页数据量的参数名，默认：limit
                }

                ,parseData: function(res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": 0, //解析接口状态
                        "msg": '', //解析提示文本
                        "count": res.total, //解析数据长度
                        "data": res.list //解析数据列表
                    }
                }
                ,cols: [[
                    // {field:'id', title: '序号', sort: true,fixed:'left'}
                    {field:'name',width:100,title: '姓名',fixed:'left'}
                    ,{field:'gender',title: '性别',sort:true}
                    ,{field:'id_number',  width: 200, title: '身份证号'}
                    ,{field:'zylevel',width:200, title: '职业等级',sort:true}
                    ,{field:'phone_number',width:150, title: '联系方式'}
                    ,{field:'ybid', width:150,title: '医保ID', sort: true}
                    ,{field:'rylb',width:150,title: '人员类别/工种',sort:true}
                    ,{field:'sbdw', width:250,title: '申报单位',sort:true}
                    ,{field:'sbdwcode', width:200,title: '申报单位机构代码',sort:true}
                    ,{field:'certificate_code', width:200,title: '证书编号'}
                    ,{field:'fzrq', width:200,title: '发证日期'}
                    ,{field:'ybbsmrq',width:200, title: '获得医保标识码日期'}
                    ,{field:'fservdate', width:200,title: '首次服务日期'}
                    ,{field:'worklength',width:200, title: '工作年限'}
                    ,{field:'status', width:200,title: '人员状态',sort:true}
                    ,{field:'serv_org', width:200,title: '护理机构',sort:true}
                    ,{field:'lastserv_org', width:200, title: '上一家护理机构', sort: true}
                    // ,{field:'history_change_time', width:200, title: '历史变更时间', sort: true}
                    ,{fixed: 'right', toolbar: '#Confirm', width: 80, title: '操作'}

                ]]
                ,page:true
            });
            ShowFirstWeekDateTitle();
            // ShowSecondWeekDateTitle();
            // 年月日选择器渲染
            laydate.render({
                elem: '#serv_start_date',
                trigger: 'click'
            });
            laydate.render({
                elem: '#serv_due_date',
                trigger: 'click'
            });
            //时间选择器
            laydate.render({
                elem: '#serv_start_time'
                ,trigger: 'click'
                ,type: 'time'
                ,format: 'HH:mm'
            });

            //选择服务时间后点击“确定”触发事件，确定服务时间
            $("#sureTime").click(function(){
                console.log("触发确定按键");
                var serv_start_date=document.getElementById('serv_start_date').value;
                var selectTime=document.getElementById('selectTime').value;
                var serv_start_time=document.getElementById('serv_start_time').value;
                var serv_worklength=document.getElementById('serv_worklength').value;
                var nursing_yb_id=document.getElementById('nursing_yb_id').value;
                var serv_end_time=document.getElementById("serv_due_date").value;
                console.log(serv_end_time);
                var selectArr = WeekDay.getValue();//获取选择的日期
                //将选择的日期转换成string字符串格式
                var chosenWeekday = [];
                for (var index=0; index < selectArr.length; index++) {
                    chosenWeekday.push(selectArr[index].value);
                }
                chosenWeekday=chosenWeekday.join();
                console.log("输出选中的时间（数组）：",chosenWeekday);
                $.ajax({
                    method:"POST"
                    ,url: "/arrangeInfo/choseServTime"
                    ,data: {StartDate:serv_start_date,
                            SelectTime:selectTime,
                            StartTime:serv_start_time,
                            ServWorkLength:serv_worklength,
                            StaffYbid:nursing_yb_id,
                            ChosenWeekday:chosenWeekday,
                            ArrangeID:ArrangeID,
                            EndDate:serv_end_time

                            }
                    ,dataType: "JSON"
                    ,success: function(res){
                        console.log("成功");
                        console.log(res.msg);
                        if(res.msg=="SuccessfullyChoseServTime"){
                            layer.msg("提交成功",{icon: 1, time: 1500},function(){
                                parent.location.reload();
                            });
                        }
                        else if(res.msg=="config"){
                            console.log("此护工该时间段存在冲突");
                            layer.msg("此护工该时间段存在冲突",{ icon: 5,anim: 6,offset: "auto"});
                        }
                        else if(res.msg=="noStaff"){
                            layer.msg("不存在该护工",{ icon: 5,anim: 6,offset: "auto"});
                        }
                        else if(res.msg=="IncompleteData"){
                            layer.msg("请填入完整数据",{ icon: 5,anim: 6,offset: "auto"});
                        }
                        else if(res.msg=="ChangeFail"){
                            layer.msg("长期不变订单以失效",{ icon: 5,anim: 6,offset: "auto"});
                        }
                        else if(res.msg=="SuccessfullyChange"){
                            layer.msg("长期变更成功",{icon: 1, time: 1500},function(){
                                parent.location.reload();
                            });
                            //layer.msg("长期变更成功",{ icon: 5,anim: 6,offset: "auto"});
                        }else if(res.msg=="SuccessfullyShortChange"){
                            layer.msg("短期变更成功",{icon: 1, time: 1500},function(){
                                parent.location.reload();
                            });
                            //layer.msg("短期变更成功",{ icon: 5,anim: 6,offset: "auto"});
                        }
                    }
                    ,error:function (data) {
                        console.log("提交失败");
                        layer.msg("提交失败",{ icon: 5,anim: 6,offset: "auto"});
                    }
                })
            })

            // 护工搜索功能
            var active = {
                // 信息页面-搜索功能
                search: function(){
                    var send_name = $('#nursing_name');
                    var send_ybid = $('#nursing_ybid');
                    var send_id=$('#nursing_id');
                    console.log("搜索的护工姓名是"+send_name.val());
                    console.log("搜索的医保ID是"+send_ybid.val());
                    console.log("搜索的身份证号是"+send_id.val());

                    //执行重载
                    table.reload('nursingArrange', {
                        url: '/arrangeInfo/searchArrangeNursing',
                        method:'post',
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        ,where: {
                            NursingName: send_name.val(),
                            NursingYbid: send_ybid.val(),
                            NursingID:send_id.val()
                        }
                    }, 'data');
                }
            };
            $('.SearchNursing .layui-btn').on('click', function () {
                console.log("排程页面：触发按键");
                var type = $(this).data('type');
                console.log("type:"+type);
                active[type] ? active[type].call(this) : '';
                console.log("结束");
            });

            //自动生成表格
            var all=null;
            var index=0;
            for(var row=0;row<24;row++){
                var tableData="<tr>";
                for(var col=0;col<7;col++){
                    tableData+='<td class="content confont" style="height: 52px;width:120px" id=' + index + '></td>';
                    index++;
                }
                tableData+="</tr>";
                all+=tableData;
            }
            //现在tableData已经生成好了，把他赋值给tbody
            $("#tbody1").html(all);
            //监听护工表格的确定按键，表格显示护工的日程安排

            $("#thisWeek").click(function () {
                //更改表头
                ShowFirstWeekDateTitle();
                //清空表格
                for(var y=0;y<168;y++){document.getElementById(y).innerText="";}
                var StaffName=document.getElementById("chosen_name").value;
                var StaffYbid=document.getElementById("chosen_ybid").value;
                var whichWeek="本周";
                if(StaffName!=null||StaffYbid!=null){
                    $.ajax({
                        type:"GET"
                        ,url: "/arrangeInfo/findNurseArrangement"
                        ,data: {StaffYbid:StaffYbid,
                                whichWeek:whichWeek}
                        ,dataType: "JSON"
                        ,success: function(result) {
                            console.log("成功获取");
                            console.log(result);
                            for(var y=0;y<168;y++){
                                document.getElementById(y).innerText="";
                            }
                            for(var i=0;i<result.length;i++){
                                var UnixTime=result[i].StartTime;
                                result[i].StartTime=FormatDateTime(UnixTime);//将unix时间戳转为正常时间
                                var StartTime=result[i].StartTime;//将正常时间赋值给StartTime
                                var WorkLength=result[i].WorkLength;
                                var chosenDay=result[i].ChosenDay.split(',');//将字符串转为数组
                                //在表格相应位置显示老人姓名及医保ID
                                for(var j=0;j<chosenDay.length;j++){
                                    var CurrentWorkday=chosenDay[j]; //获取当前工作日数组中的值
                                    var index=ShowDateinTable(StartTime,CurrentWorkday);//计算出该工作时间对应的表格下标
                                    for(var hour=0;hour<WorkLength;hour++){ //对于工作时长大于1h的进行循环输出
                                        var AllIndex=index+7*hour;
                                        document.getElementById(AllIndex).innerHTML=result[i].ElderName+result[i].ElderYbid+StartTime;
                                    }
                                }
                            }
                        }
                    });
                }

            });

            $("#nextWeek").click(function () {
                //更改表头
                ShowSecondWeekDateTitle();
                //清空表格
                for(var y=0;y<168;y++){document.getElementById(y).innerText="";}
                var StaffName=document.getElementById("chosen_name").value;
                var StaffYbid=document.getElementById("chosen_ybid").value;
                var whichWeek="下周";
                if(StaffName!=null||StaffYbid!=null){
                    $.ajax({
                        type:"GET"
                        ,url: "/arrangeInfo/findNurseArrangement"
                        ,data: {StaffYbid:StaffYbid,
                            whichWeek:whichWeek}
                        ,dataType: "JSON"
                        ,success: function(result) {
                            console.log("成功获取");
                            console.log(result);
                            for(var y=0;y<168;y++){
                                document.getElementById(y).innerText="";
                            }
                            for(var i=0;i<result.length;i++){
                                var UnixTime=result[i].StartTime;
                                result[i].StartTime=FormatDateTime(UnixTime);//将unix时间戳转为正常时间
                                var StartTime=result[i].StartTime;//将正常时间赋值给StartTime
                                var WorkLength=result[i].WorkLength;
                                var chosenDay=result[i].ChosenDay.split(',');//将字符串转为数组
                                //在表格相应位置显示老人姓名及医保ID
                                for(var j=0;j<chosenDay.length;j++){
                                    var CurrentWorkday=chosenDay[j]; //获取当前工作日数组中的值
                                    var index=ShowDateinTable(StartTime,CurrentWorkday);//计算出该工作时间对应的表格下标
                                    for(var hour=0;hour<WorkLength;hour++){ //对于工作时长大于1h的进行循环输出
                                        var AllIndex=index+7*hour;
                                        document.getElementById(AllIndex).innerHTML=result[i].ElderName+'<br>'+result[i].ElderYbid;
                                    }
                                }
                            }
                        }
                    });
                }
            });

            table.on('tool(nursingArrange)', function(obj) {
                var data = obj.data;
                var NursingYbid=data.ybid;
                var NursingName=data.name;
                var whichWeek="本周";
                if (obj.event === 'sure') {
                    console.log("按下确定按钮");
                    document.getElementById("chosen_name").value=NursingName;
                    document.getElementById("chosen_ybid").value=NursingYbid;
                    $.ajax({
                        type:"GET"
                        ,url: "/arrangeInfo/findNurseArrangement"
                        ,data: {NursingYbid:NursingYbid,
                                whichWeek:whichWeek}
                        ,dataType: "JSON"
                        ,success: function(result) {
                            console.log("成功获取");
                            console.log(result);
                            let myset=new Set();
                            for(var y=0;y<168;y++){
                                document.getElementById(y).innerText="";
                            }
                            for(var i=0;i<result.length;i++){
                                var UnixTime=result[i].StartTime;
                                var UnixTime1= result[i].EndTime;
                                result[i].StartTime=FormatDateTime(UnixTime);//将unix时间戳转为正常时间
                                result[i].EndTime=FormatDateTime(UnixTime1);
                                var StartTime=result[i].StartTime;//将正常时间赋值给StartTime
                                var EndTime=result[i].EndTime;
                                var WorkLength=result[i].WorkLength;
                                var chosenDay=result[i].ChosenDay.split(',');//将字符串转为数组
                                //在表格相应位置显示老人姓名及医保ID
                                for(var j=0;j<chosenDay.length;j++){
                                    var CurrentWorkday=chosenDay[j]; //获取当前工作日数组中的值
                                    var index=ShowDateinTable(StartTime,CurrentWorkday);//计算出该工作时间对应的表格下标
                                    //对于工作时长大于1h的进行循环输出
                                    console.log(myset);
                                    while(myset.has(index)){
                                        index=index+7;
                                    }
                                    myset.add(index);
                                    var AllIndex=index;

                                    document.getElementById(AllIndex).innerHTML=result[i].ElderName+'<br>'+StartTime+'~'+EndTime;

                                }
                            }
                        }
                    });
                }
            });
        })
    }
});
